package com.bolinfest.editor;

import java.util.Set;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.users.User;
import com.google.appengine.repackaged.com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;

/**
 * Each user is associated with a UserPreferences object.
 *
 * @author bolinfest@gmail.com (Michael Bolin)
 */
@PersistenceCapable
public class UserPreferences {

  @PrimaryKey
  private String userId;

  @Persistent
  private Set<String> documentIds;

  public UserPreferences(User user) {
    Preconditions.checkNotNull(user);
    userId = user.getUserId();
    documentIds = ImmutableSet.of();
  }

  public Set getDocumentIds() {
    return documentIds;
  }

  public void addDocumentId(String documentId) {
    Preconditions.checkNotNull(documentId);
    if (!documentIds.contains(documentId)) {
      Set<String> newDocumentIds = Sets.newHashSet(documentIds);
      newDocumentIds.add(documentId);
      this.documentIds = ImmutableSet.copyOf(newDocumentIds);
    }
  }

  public static UserPreferences getPrefsForUser(User user, PersistenceManager pm) {
    // TODO(bolinfest): Find out the right way to do this in AppEngine.
    UserPreferences prefs;
    try {
      prefs = pm.getObjectById(UserPreferences.class, user.getUserId());
    } catch (JDOObjectNotFoundException e) {
      prefs = new UserPreferences(user);
      pm.makePersistent(prefs);
    }
    return prefs;
  }
}
